package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"serve/internal/global/model"

	"serve/internal/svc"
	"serve/videoSrv"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoClassAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoClassAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoClassAddLogic {
	return &VideoClassAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoClassAddLogic) VideoClassAdd(in *videoSrv.VideoClassAddRequest) (*videoSrv.VideoClassAddResponse, error) {
	// todo: add your logic here and delete this line
	var VideoClass = model.VideoClass{
		Status:    1,
		Title:     in.Title,
		ImageUrl:  in.ImageUrl,
		Des:       in.Des,
		ShowCount: 0,
		Tag:       in.Tag,
	}
	var video_class_bg = model.DB.Begin()
	if err := model.DB.Create(&VideoClass).Error; err != nil {
		video_class_bg.Rollback()
		return nil, err
	}
	for _, video := range in.Videos {
		var videos model.Video
		model.DB.Where("id = ?", video).Find(&videos)
		if videos.ClassId != 0 {
			video_class_bg.Rollback()
			return nil, fmt.Errorf("视频" + fmt.Sprintln(video) + "已有剧集")
		}
		if err := video_class_bg.Updates(&model.Video{
			Model: gorm.Model{
				ID: uint(video),
			},
			ClassId: int(VideoClass.ID),
		}).Error; err != nil {
			video_class_bg.Rollback()
			return nil, err
		}
	}
	video_class_bg.Commit()
	return &videoSrv.VideoClassAddResponse{}, nil
}
